<?php

namespace IDock\Insurance\ZFIC\Request;

use IDock\IDock\IDockEnums;
use IDock\Insurance\ZFIC\Response\InsurancePriceQueryResponse;
use IDock\Insurance\ZFIC\ZFICEnums;
use IDock\Visitor\NonCar\NonCarProductVisitor;
use IDock\Visitor\Premium\PremiumChargingPileVisitor;
use IDock\Visitor\Premium\PremiumCoverageVisitor;
use IDock\Visitor\Premium\PremiumInquiryVisitor;

class OfferOrderPriceRequest extends AllZFICRequest
{

    protected $urlTip = '保费计算接口';

    protected $route = 'order/api/order/offer';

    protected $response = InsurancePriceQueryResponse::class;

    protected $coverageList = [];

    public $isNewEnergy = 0;//是否是新能源
    /**
     * @var PremiumInquiryVisitor $visitor
     */
    protected $visitor;

    public function generate(): array
    {
        $this->isNewEnergy = $this->visitor->getVehicleVisitor()->isNewEnergy;
        $selfPricingFactor = $this->visitor->getExtInfoVisitor()->selfPricingFactor ?: 0;

        $param = [
            'platOrderNo' => $this->visitor->getExtInfoVisitor()->argc['platOrderNo'],
            'businessNo' => $this->visitor->getExtInfoVisitor()->argc['businessNo'],
            'kindList' => $this->getKindList(),
            'rateList' => [
//                [
//                    'platOrderNo' => $this->visitor->getExtInfoVisitor()->argc['platOrderNo'],
//                    'riskCode' => '0808',
//                    'profitType' => 'UNIT',
//                    'profitCode' => 'F05',
//                    'profitName' => '自主定价系数',
//                    'rate' => strval(round($selfPricingFactor * 100, 2)),
//                ]
            ],//优惠信息
            'jqImmediateFlag' => intval($this->visitor->ciEffectFlag) ?: '0',
            'immediateFlag' => intval($this->visitor->biEffectFlag) ?: '0',
            'taxRelifFlag' => ZFICEnums::$taxTypeCode[$this->visitor->getCarTaxVisitor()->taxTypeCode],
            'taxPayerName' => $this->visitor->getCarTaxVisitor()->taxpayerName,
            'certiType' => ZFICEnums::$certificateTypeCode[$this->visitor->getCarTaxVisitor()->taxpayerCertificateTypeCode],
            'identifyNumber' => $this->visitor->getCarTaxVisitor()->taxpayerCertificateNo,
            'taxCompancyCode' => '',//税务机关代码
            'taxCompancyName' => '',//税务机关名称
            'relifReason' => '',//减免原因
            'paidFreeCertificate' => '',//减免税凭证/完税凭证号
            'deductionDueType' => '',//减免税方案代码
            'freeRate' => '',//减税比例
            'negotiatedActualValue' => $this->visitor->getVehicleVisitor()->actualValue,//协商实际价格
            'renewalAnswerJQ' => '',//交强险转保车验证答案
            'renewalAnswerSY' => '',//商业险转保车验证答案
            'querySequenceNoJQ' => '',//交强险投保查询码
            'querySequenceNoSY' => '',//商业险投保查询码
            'renewalFlag0801' => '',//交强险转保标志
            'renewalFlag0802' => '',//商业险转保标志
            'entireExpDiscount' => $this->visitor->getExtInfoVisitor()->expectedDiscount,//期望折扣
            'deviceList' => [],//新增设备数据列表
            'chargingPostList' => $this->getChargingPostList(),//新增源充电桩信息
            'businessLevel' => $this->visitor->getExtInfoVisitor()->argc['businessLevel'] ?? '',//业务等级
            'taxDocumentDate' => '',//完税凭证填发日期
            'taxPaidAreaCode' => '',//完税凭证地区

        ];
        if ($param['jqImmediateFlag']) {

        }
        //随车驾意方案信息
        $this->nonCarPlan($param);

        if (empty($param['taxRelifFlag']) && $this->visitor->getCarTaxVisitor()->taxTypeCode != 'T07') {
            throw new \Exception("不支持的缴税类型");
        }
        if (empty($param['certiType'])) {
            throw new \Exception("不支持的纳税人证件类型");
        }
        if (in_array($this->visitor->getCarTaxVisitor()->taxTypeCode, ['T02', 'T03', 'T04'])) {
            $param['taxCompancyCode'] = $this->visitor->getCarTaxVisitor()->taxDepartmentCode;
            $param['taxCompancyName'] = $this->visitor->getCarTaxVisitor()->taxDepartment;
            $param['relifReason'] = $this->visitor->getCarTaxVisitor()->taxReductionReasonCode;
            $param['paidFreeCertificate'] = $this->visitor->getCarTaxVisitor()->taxDocumentNumber;
            $param['deductionDueType'] = ZFICEnums::$taxReductionCode[$this->visitor->getCarTaxVisitor()->taxReductionCode];
            $param['freeRate'] = $this->visitor->getCarTaxVisitor()->taxFreeRate;
            $param['taxDocumentDate'] = $this->visitor->getCarTaxVisitor()->taxDocumentDate;//完税凭证填发日期
            $param['taxPaidAreaCode'] = $this->visitor->getCarTaxVisitor()->taxPaidAreaCode;//完税凭证地区
        }
        return $param;
    }

    private function getKindList()
    {
        $list = $this->visitor->getCoverageVisitorList();
        $originalList = $this->getCoverageList();
        $kindList = [];
        /*** @var PremiumCoverageVisitor $val */
        foreach ($list as $val) {
            $originalKind = $originalList[ZFICEnums::$coverageCode[$val->coverageCode]] ?? [];
            $kindArr = [
                "kindCode" => ZFICEnums::$coverageCode[$val->coverageCode],
                "amount" => round($val->amount, 2),
                "hasRelatedInd" => '0',
            ];
            if ($kindArr['kindCode'] == 'BZ') {
                $kindArr['amount'] = $originalKind['amounts'][0]['amount'];
            }
            if ($kindArr['kindCode'] == '001') {
                $kindArr['amount'] = $this->visitor->getVehicleVisitor()->actualValue;
            }
            if (empty($kindArr['kindCode'])) {
                throw new \Exception("不支持" . IDockEnums::$coverageCode[$val->coverageCode] . "险种,请更换");
            }

            //附加医保外医疗费用责任险（第三者责任保险）保额验证
            if ($kindArr['kindCode'] == '0050' or $kindArr['kindCode'] == '0077') {
                if (!in_array($kindArr['amount'],['10000','20000','50000','100000'])) {
                    throw new \Exception('附加医保外医疗费用责任险（第三者责任保险）只支持保额：10000，20000，50000，100000');
                }
            }

            if (in_array($kindArr['kindCode'], ['0041', '0055', '0056', '023', '0078', '0074', '0082'])) {
                //人员责任险 司机
                $kindArr['unitAmount'] = $val->amount;
                $kindArr['quantity'] = 1;
            }
            if (in_array($kindArr['kindCode'], ['0044', '024', '0075', '0079', '0083', '0057', '0058'])) {
                //人员责任险 乘客
                if (in_array($kindArr['kindCode'], ['0044', '024'])) {
                    $kindArr['unitAmount'] = $val->unitAmount;
                }
                if (in_array($kindArr['kindCode'], ['0075', '0079', '0083', '0057', '0058'])) {
                    $kindArr['unitAmount'] = $val->amount;
                }
                $kindArr['quantity'] = $this->visitor->getVehicleVisitor()->vehicleSeat - 1;
            }
            if (($originalKind['amounts'][0]['valueType'] ?? '')) {
                $kindArr['valueType'] = $originalKind['amounts'][0]['valueType'];
            }
            //服务次数
            if ($kindArr['kindCode'] == '0045' or $kindArr['kindCode'] == '0064') {
                $kindArr['serviceTimes'] = $val->serviceTimes;
            }
            if ($val->deductionRate) {
                switch ($val->deductionRate) {
                    case '5':
                        $rate = '1';
                        break;
                    case '10':
                        $rate = '2';
                        break;
                    case '15':
                        $rate = '3';
                        break;
                    case '20':
                        $rate = '4';
                        break;
                    default :
                        $rate = '';
                }
                $kindArr['absoluteDeductibleRate'] = $rate;
            }
            $kindArr['amount'] = round($kindArr['amount'], 2);
            $kindList[] = $kindArr;
        }
        return $kindList;
    }

    private function getChargingPostList()
    {
        $list = $this->visitor->getChargingPileVisitorList();
        $chargingList = [];

        /** @var PremiumChargingPileVisitor $val */
        foreach ($list as $key => $val) {
            $chargingList[] = [
                'chargingPostType' => $val->chargingPileType,//充电桩型号
                'chargingPostCode' => $val->chargingPileCode,//充电桩编码
                'chargingPostAddress' => $val->chargingPileAddress,//充电桩地址
                'chargingPostAddressType' => ZFICEnums::$chargingPileAddressType[$val->chargingPileAddressType],//充电桩安装地点类型
                'chargingPostKind' => ZFICEnums::$chargingPileKind[$val->chargingPileKind],//充电桩种类
                'chargingPostYearLimit' => ZFICEnums::$chargingPileYearLimit[$val->chargingPileYearLimit],//充电桩使用年限
                'lossSumLimit' => $val->lossAmount,//损失保险保额
                'liabilitySumLimit' => $val->liabilityAmount,//责任保险限额
                'itemNo' => strval($key + 1),//标的序号
                'serialNo' => $val->seqNo,//序列号
                'kindCode' => $val->lossAmount ? '0060' : '0061',//险别代码
            ];

        }
        return $chargingList;
    }

    private function getCoverageList()
    {
        $list = [];
        foreach ($this->coverageList as $val) {
            $list[$val['kindCode']] = $val;
        }
        return $list;
    }

    /**
     * @param $list
     * @return $this
     */
    public function setCoverageList($list)
    {
        $this->coverageList = $list;
        return $this;
    }

    public function getStaffConfig(&$chalCode, &$userCode)
    {
        $chalCode = $this->visitor->getExtInfoVisitor()->argc['chalCode'] ?? '';
        $userCode = $this->visitor->getExtInfoVisitor()->argc['userCode'] ?? '';
    }

    /**
     * 非车请求参数
     * @param $param
     * @return void
     * @version 4.0
     */
    private function nonCarPlan(&$param): void
    {

        $visitor = $this->visitor->getNonCarInquiryVisitor();
        $oneProduct = $visitor->getNonCarList();
        if (!count($oneProduct)) {
            return;
        }
        $oneProduct = array_shift($oneProduct);
        /*** @var $oneProduct NonCarProductVisitor */

        $param['driAccPlan'] = [
            'userCode' => $visitor->argc['NCUserCode'] ?? '',
            'productCode' => $oneProduct->productCode,
            'planCode' => $oneProduct->planCode,
            'uwCountJY' => $oneProduct->insuredNum
        ];
    }

}
